//
//  AVDUsersVC.m
//  AVD_Demo
//
//  Created by 3tee on 2022/11/30.
//

#import "AVDUsersVC.h"

@interface AVDUsersVC ()<UITableViewDelegate,UITableViewDataSource,AVDUserManagerDelegate>

@property(nonatomic, strong)UITableView *usersTab;
@property(nonatomic, strong)AVDUserManager *um;

@end

@implementation AVDUsersVC

- (void)dealloc{
    NSLog(@"AVDUsersVC dealloc");
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}


- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [self setupUI];
    [self refreshUser];
}

- (void)refreshUser{
    NSString *roomid = [[NSUserDefaults standardUserDefaults] stringForKey:roomIdKey];
    AVDRoom *room = [AVDRoom obtain:roomid];
    self.um = [AVDUserManager getUserManager:room];
    self.um.delegate = self;
}

- (void)setupUI{
    self.title = @"参会者列表";
    self.usersTab = [[UITableView alloc]initWithFrame:CGRectMake(0, k_Height_NavBar,SCREEN_WIDTH , SCREENH_HEIGHT-k_Height_NavBar) style:UITableViewStylePlain];
    self.usersTab.delegate = self;
    self.usersTab.dataSource = self;
    self.usersTab.tableHeaderView = [UIView new];
    [self.view addSubview:self.usersTab];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.um.participants.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AVDUser *user = self.um.participants[indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"user_cell"];
    if(cell == nil){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"user_cell"];
        cell.textLabel.text = user.userName;
        
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)onUserJoinNotify:(AVDUser *)user{
    NSString * msg = [NSString stringWithFormat:@"用户:%@加入会议",user.userName];
    [self toastMsg:msg];
    [self.usersTab reloadData];
}

- (void)onUserLeaveNotify:(AVDUser *)user reason:(AVDResult)reason{
    NSString * msg = [NSString stringWithFormat:@"用户:%@离开会议",user.userName];
    [self toastMsg:msg];
    [self.usersTab reloadData];
}

- (void)toastMsg:(NSString *)msg{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.label.text = msg;
    hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
    [hud hideAnimated:YES afterDelay:2.f];
}

@end
